package br.com.dev.tcc.view;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import br.com.dev.tcc.R;
import br.com.dev.tcc.model.HomeModel;
import br.com.dev.tcc.singleton.LocationSingleton;
import br.com.dev.tcc.util.ConnectivityUtil;
import br.com.dev.tcc.util.GpsUtil;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;

/**
 * Activity da tela inicial, controla o fluxo de navegacao de telas e as
 * chamadas telefonicas para numeros emergenciais. Monitora o gps para obter
 * localização.
 * 
 * @see LocationListener
 */
public class HomeActivity extends SherlockActivity implements LocationListener {

	private HomeView view;
	private HomeModel model;
	private LocationManager locationManager;

	private ConnectivityUtil conUtil;
	private GpsUtil gpsUtil;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.grid_rodape);
		setModel();
		setView();
	}

	@Override
	protected void onResume() {

		super.onResume();
		requestGps();
	}

	@Override
	protected void onDestroy() {

		super.onDestroy();
		cancelGpsRequest();
	}

	private void setUtils() {

		conUtil = new ConnectivityUtil(this);
		gpsUtil = new GpsUtil(locationManager);
	}

	private void setModel() {

		model = new HomeModel(this);
	}

	private void setView() {

		view = new HomeView(this);
		view.setGridViewItens(model.getGridItens());
		view.setOnItemClickListener(new GridClickListener());
		view.setAlertClickListener(new AlertClickListener());
	}

	/**
	 * Chamado automaticamente quando o usuario clica no icone de telefone,
	 * monta o menu com as opcoes de chamada
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		menu = view.buildTelefonesMenu(menu, model.getTelefones());

		return super.onCreateOptionsMenu(menu);
	}

	/**
	 * "Escuta" os toques nos icones da grade e abre outra tela de acordo com o
	 * item selecionado
	 */
	class GridClickListener implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> av, View v, int position, long id) {

			if (model.getGridItens().get(position).hasIntent())
				HomeActivity.this.startActivity(model.getGridItens()
						.get(position).getIntent());
		}
	}

	/**
	 * "Escuta" o toque no layout de aviso e abre a tela de configuracoes para
	 * ativacao d gps
	 */
	class AlertClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {

			startActivity(GpsUtil.getGpsSettingsIntent());
		}
	}

	private void setAlertText(boolean isGpsEnabled, boolean isGpsNetEnabled,
			boolean isNetworkConnected) {

		view.setAlertText(model.getAlertText(isGpsEnabled, isGpsNetEnabled,
				isNetworkConnected));
	}

	/*
	 * Metodos para controle e monitoramento do GPS
	 */

	private void requestGps() {

		try {

			locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
			locationManager.requestLocationUpdates(
					LocationManager.GPS_PROVIDER, 0, 0, this);
			locationManager.requestLocationUpdates(
					LocationManager.NETWORK_PROVIDER, 0, 0, this);

			setUtils();

			setAlertText(gpsUtil.isGpsEnabled(), gpsUtil.isGpsNetEnabled(),
					conUtil.isConnected());
		}
		/*
		 * Cai no catch se por algum motivo o usuario conseguir instalar num
		 * aparelho que nao suporta gps
		 */
		catch (IllegalArgumentException e) {

			setAlertText(false, false, false);
		}
	}

	private void cancelGpsRequest() {

		if (locationManager != null)
			locationManager.removeUpdates(this);
	}

	@Override
	public void onLocationChanged(Location location) {

		LocationSingleton.getInstance().setLocation(location);
		setAlertText(gpsUtil.isGpsEnabled(), gpsUtil.isGpsNetEnabled(),
				conUtil.isConnected());
	}

	@Override
	public void onProviderDisabled(String provider) {

		setAlertText(gpsUtil.isGpsEnabled(), gpsUtil.isGpsNetEnabled(),
				conUtil.isConnected());
	}

	@Override
	public void onProviderEnabled(String provider) {

		setAlertText(gpsUtil.isGpsEnabled(), gpsUtil.isGpsNetEnabled(),
				conUtil.isConnected());
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
	}
}
